/**
 * Created by Harrie on 2015/10/12 0012.
 */

var MsgType = {
    Msg: 'message',
    Info: 'information'
};

var Message = function (type, date, props) {
    this.type = type;
    this.date = new Date(date);
    this.msg = props.msg;
    this.name = props.name;
    this.self = props.self;
};

var LoginBox = Vue.extend({
    template: $("#loginBoxTemplate").html(),
    methods: {
        doLoginCheck: function (roomId) {
            if (!this.$parent.userName)
                alert("请输入昵称！");
            else
                this.$dispatch('loginEvent', roomId);
        },
        toCreateRoom: function () {
            this.$parent.step = 2;
        }
    }
});

var CreateRoomBox = Vue.extend({
    template: $("#createRoomBoxTemplate").html(),
    data: function () {
        return {
            roomName: ''
        }
    },
    methods: {
        doCreateRoomCheck: function () {
            if (!this.roomName)
                alert("请输入房间名称！");
            else
                this.$dispatch('createRoomEvent', this.roomName);
        },
        createRoomCancel: function () {
            this.$parent.step = 1;
        }
    }
});

var ChatBox = Vue.extend({
    template: $("#chatBoxTemplate").html(),
    data: function () {
        return {
            postMsg: '',
            faceSelVisible: [false, false]
        }
    },
    methods: {
        onPost: function (event) {
            if (event.shiftKey) {
                this.doPost();
                event.preventDefault();
            }
        },
        doPost: function () {
            if (this.postMsg && this.postMsg.trim() != '') {
                this.$dispatch('postEvent', this.postMsg);
                this.postMsg = '';
            }
        },
        doPostImg: function (event) {
            if (!this.$parent.allowPostImg)return;
            var that = this;
            var clipboardData = event.clipboardData;
            if (clipboardData && clipboardData.items && clipboardData.types) {
                var items = clipboardData.items || [],
                    types = clipboardData.types || [],
                    item;
                for (var i = 0; i < types.length; i++) {
                    if (types[i] === 'Files')
                        item = items[i];
                }
                if (item && item.kind == 'file' && item.type.match(/^image\//i)) {
                    var file = item.getAsFile(),
                        reader = new FileReader();
                    if (!reader)return;
                    reader.onload = function (e) {
                        that.$dispatch('postImgEvent', e.target.result);
                    };
                    reader.readAsDataURL(file);
                }
            }
        },
        openImgSel: function (event) {
            var that = this;
            var files = event.target.files;
            if (!files || files.length == 0)return;
            var file = files[0],
                reader = new FileReader();
            if (!reader)return;
            reader.onload = function (e) {
                that.$dispatch('postImgEvent', e.target.result);
            };
            reader.readAsDataURL(file);
        },
        quoteUser: function (name) {
            this.postMsg += '@' + name + " ";
            $("#postMsgText").focus();
        },
        clearMsg: function () {
            this.$dispatch('clearMsgEvent');
        },
        doLogout: function () {
            this.$dispatch('logoutEvent');
        },
        faceSelToggle: function (id) {
            this.$set('faceSelVisible[' + id + ']', !this.faceSelVisible[id]);
        },
        faceSelect: function (id, category, index) {
            this.faceSelToggle(id);
            this.postMsg += '[' + category + ':' + index + ']';
            $("#postMsgText").focus();
        }
    }
});

Vue.component('login-box', LoginBox);
Vue.component('create-room-box', CreateRoomBox);
Vue.component('chat-box', ChatBox);

var minechat = new Vue({
    el: '#app',
    data: {
        step: 0,//0=连接  1=登录  2=创建房间  3=聊天室
        allowPostImg: false,
        isBackground: false,
        newMsgCount: 0,
        socket: null,
        userName: window.localStorage['userName'] || 'Unnamed',
        roomName: '',
        rooms: [],
        users: [],
        msgList: []
    },
    ready: function () {
        var that = this;
        this.$watch('step', function () {
            switch (that.step) {
                case 0:
                    break;
                case 1:
                    that.socket.on('roomsUpdate', function (date, data) {
                        that.rooms = data.rooms;
                    });
                    that.socket.on('loginFail', function (date, data) {
                        alert(data.msg);
                    });
                    that.socket.on('loginSuccess', function (date, data) {
                        that.step = 3;
                        that.roomName = data.roomName;
                        that.users = data.users;
                        that.msgList = [];
                        console.log(data.allowPostImg);
                        that.allowPostImg = data.allowPostImg;
                        that.msgList.push(new Message(MsgType.Info, date, {msg: data.msg}));
                    });
                    that.socket.off('postSuccess');
                    that.socket.off('newMsg');
                    that.socket.off('usersUpdate');
                    that.socket.emit('fetchRooms');
                    break;
                case 2:
                    break;
                case 3:
                    that.socket.on('postSuccess', function (date, data) {
                        that.msgList.push(new Message(MsgType.Msg, date, {
                            msg: data.msg,
                            name: data.userName,
                            self: true
                        }));
                    });
                    that.socket.on('newMsg', function (date, data) {
                        that.msgList.push(new Message(MsgType.Msg, date, {
                            msg: data.msg,
                            name: data.userName,
                            self: false
                        }));
                        if (that.isBackground) {
                            that.newMsgCount++;
                        }
                    });
                    that.socket.on('usersUpdate', function (date, data) {
                        that.users = data.users;
                        that.msgList.push(new Message(MsgType.Info, date, {msg: data.msg}));
                    });
                    that.socket.on('disconnect', function () {
                        that.step = 0;
                        that.init();
                    });
                    that.socket.off('roomsUpdate');
                    that.socket.off('loginFail');
                    that.socket.off('loginSuccess');
                    break;
            }
        });
        this.$watch('msgList', function () {
            $("#postMsgText").focus();
            setTimeout(function () {
                $("#msgBox").animate({
                    scrollTop: $("#msgBox")[0].scrollHeight
                }, 300);
            }, 100);
        });
        $(window).blur(function () {
            that.isBackground = true;
        });
        $(window).focus(function () {
            that.isBackground = false;
            that.newMsgCount = 0
        });
        this.$watch('newMsgCount', function () {
            if (that.newMsgCount)
                document.title = 'Minechat[' + that.newMsgCount + '条新消息]';
            else
                document.title = 'Minechat';
        });
        this.init();
    },
    methods: {
        init: function () {
            var that = this;
            this.socket = io.connect('', {"force new connection": true});
            this.socket.on('connect', function () {
                that.step = 1;
            });
        }
    },
    events: {
        'loginEvent': function (roomId) {
            this.socket.emit('login', roomId, this.userName);
            window.localStorage['userName'] = this.userName;
        },
        'logoutEvent': function () {
            this.socket.emit('logOut');
            this.step = 1;
        },
        'postEvent': function (msg) {
            this.socket.emit('postMsg', msg);
        },
        'postImgEvent': function (imgData) {
            this.socket.emit('postImg', imgData);
        },
        'clearMsgEvent': function () {
            this.msgList = [];
        },
        'createRoomEvent': function (roomName) {
            this.socket.emit('createRoom', roomName, this.userName);
        }
    }
});

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};